package cn.xueden.system.service.impl;

import cn.xueden.system.converter.NoticeConverter;
import cn.xueden.system.mapper.NoticeMapper;
import cn.xueden.system.model.entity.Notice;
import cn.xueden.system.model.form.NoticeForm;
import cn.xueden.system.model.vo.NoticeVO;
import cn.xueden.system.service.INoticeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**功能描述：公告服务实现类
 * @author:梁志杰
 * @date:2025/6/10
 * @description:cn.xueden.system.service.impl
 * @version:1.0
 */
@Service
@RequiredArgsConstructor
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements INoticeService {

    private final NoticeConverter noticeConverter;

    /**
     *  获取公告分页数据
     * @param pageNum
     * @param pageSize
     * @param title
     * @return
     */
    @Override
    @Cacheable(
            // 指定缓存名称
            value = "noticeList",
            key = "'page_' + #pageNum + '_' + #pageSize + '_' + #title",
            unless = "#result == null || #result.records.isEmpty()" // 空结果不缓存
    )
    public Page<NoticeVO> getNoticePaging(Integer pageNum, Integer pageSize, String title) {
        Page<Notice> page = new Page<>(pageNum,pageSize);
        Page<NoticeVO> noticePage = baseMapper.getNoticePaging(page, title);
        return noticePage;
    }

    /**
     * 添加公告
     * @param noticeForm
     * @return
     */
    @Override
    @CacheEvict(value = "noticeList",allEntries = true)
    public boolean addNotice(NoticeForm noticeForm) {
        Notice notice = noticeConverter.fromToEntity(noticeForm);
        boolean result = this.save(notice);
        return result;
    }

    /**
     * 删除公告
     * @param ids
     * @return
     */
    @Override
    @CacheEvict(value = "noticeList",allEntries = true)
    public boolean deleteNotice(String ids) {
        // 转换为集合
        List<Integer> noticeIds = Arrays.stream(ids.split(","))
                .map(Integer::parseInt)
                .toList();
        // 删除公告
        return this.removeBatchByIds(noticeIds);
    }

    /**
     * 删除单条公告
     * @param id
     * @return
     */
    @Override
    @CacheEvict(value = "noticeList",allEntries = true)
    public boolean deleteNoticeById(Long id) {
        return this.removeById(id);
    }

    /**
     * 修改公告
     * @param noticeForm
     * @return
     */
    @Override
    @CacheEvict(value = "noticeList",allEntries = true)
    public boolean updateNotice(NoticeForm noticeForm) {
        return this.updateById(noticeConverter.fromToEntity(noticeForm));
    }
}
